<?php

namespace app\agentapi\model;
use think\Cache;
use think\Db;
use think\Log;
/**
 *登录模型类
 */
class User extends Base{
    private $token;
    /**
     * 小程序登录
     */
    public function agentLogin($phone,$password,$code){
        //验证账户名密码
        $userInfo=Db::name('love_admin_user')->where(['user_name'=>$phone,'password'=>md5($password)])->field('password',true)->find();
            if(empty($userInfo)){//不存在
                return ['code'=>-1,'data'=>[]];
            }else{
                if($userInfo['login_type']==1){
                    return ['code'=>-3,'data'=>[]];
                }
                if($userInfo['is_delete']==1){//禁用
                    return ['code'=>-2,'data'=>[]];
                }
                Cache::set($userInfo['id'].'token',md5($phone.$password),86400 * 7);//登录人token信息
                Cache::set($phone,$userInfo,86400 * 7);//登录人个人信息

                if($code){
                     $rescode=$this->wxopenid($code);
                     //Log::mylog('openid：',$rescode,'openid');
                     //更新用户openid
                    $rescode=json_decode($rescode,true);
                    Db::name('love_admin_user')->where(['id'=>$userInfo['id']])->update(['openid'=>$rescode['openid']]);
                }

                $userInfos=Db::name('love_admin_user')->where(['id'=>$userInfo['id']])->field('password',true)->find();
                return ['code'=>1,'data'=>$userInfos];
            }
    }

    public function wxopenid($code){
        $appId = 'wx0580bdcba326b43d';
        $secret = 'cf1dac072e4d51a5d5308d4cc91b487b';
        //创建请求数据
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appId}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $data = $this->curl_get_https($url);
        return $data;
    }

    public function  curl_get_https($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
}
